<template>
  <view class="wrapper">
    <t-header @back="back"
      >{{ title }}

      <template #right>
        <view style="margin-bottom: 10rpx" @click="onRecord">交易记录</view>
      </template>
    </t-header>

    <!-- <tt-navbar :left="true" :title="title" rightText="交易记录" @lclick="navBack" @rclick="jump(`/pages/shares/dzyj-record?name=${title}`)" ></tt-navbar> -->
    <view class="main-content">
      <view class="list-group">
        <view class="flex head">
          <view class="col-5 text-left"> 股票名称 </view>
          <view class="col-5 text-center"> 现价 </view>
          <view class="col-4 text-right"> 大宗交易价 </view>
          <view class="col-5 text-right">
            <!-- 总股额(股) -->
            折扣率%
          </view>
          <view class="col-5 text-center"> 操作 </view>
        </view>
        <!-- <view class="list-item flex" v-for="(item,index) in goodList" :key="index">
					<view class="col-4 text-center align-center">
						<view class="icon-1">
							沪
						</view>
						{{item.name}}
					</view>
					<view class="col-5 text-center">
						{{item.price}}
					</view>
					<view class="col-5 text-right red">
						{{item.bigPrice}}
					</view>
					<view class="col-5 text-right green">
						{{item.discount}}
					</view>
					<view class="col-5 text-center">
						{{item.action}}
					</view>
				</view> -->
        <mescroll-body
          @init="mescrollInit"
          :down="downOption"
          @down="downCallback"
          height="90%"
          :up="upOption"
          @up="upCallback"
        >
          <template v-if="list && list.length > 0">
            <view class="item" v-for="(item, index) in list" :key="index">
              <view class="flex align-center">
                <view class="col-5 align-center">
                  <image
                    class="sign"
                    :src="`/static/images/icons/${item.marketCode}.png`"
                    mode=""
                  ></image>
                  <view class="name">{{ item.title }}</view>
                  <!-- <view class="flex align-center">
									
									<view class="text-sm">{{item.code}}</view>
								</view> -->
                </view>
                <view class="col-5 text-center">
                  {{ item.cai_price }}
                </view>
                <view class="col-4 text-right red">
                  {{ item.cai_buy }}
                </view>
                <view class="col-5 text-right green">
                  {{ item.rate }}
                </view>
                <view class="col-5 flex justify-center">
                  <view @click="showBuy({ index })">手动</view>
                </view>
              </view>
            </view>
          </template>
          <template v-else>
            <view class="empty-content">
              <img src="/static/images/wushuju.png" alt="" />
              <text>空空如也</text>
            </view>
          </template>
        </mescroll-body>
      </view>
    </view>

    <tui-modal
      :show="showModal"
      custom
      @cancel="showModal = false"
      padding="40rpx"
    >
      <view class="" v-if="currentItem">
        <view class="cell">
          <view>股票名称</view>
          <view>{{ currentItem.title }}</view>
        </view>
        <view class="cell">
          <view>股票代码</view>
          <view>{{ currentItem.code }}</view>
        </view>
        <view class="cell">
          <view>当前价</view>
          <view>{{ currentItem.cai_buy }}</view>
        </view>
        <view class="cell">
          <view>可用余额</view>
          <view>{{ userInfo.property_money }}</view>
        </view>
        <view class="cell">
          <view>最大购买</view>
          <view>{{ currentItem.max_num }}</view>
        </view>
        <view class="cell">
          <view>支付金额</view>
          <view>{{ frozenMoey || 0 }}</view>
        </view>
        <view class="cell">
          <view>数量(手)</view>
          <view>
            <tui-numberbox
              :max="max"
              :value="handNum"
              @change="changeHandNum"
            ></tui-numberbox>
          </view>
        </view>
        <view class="cell" v-if="currentItem.conditioncode">
          <view>密钥</view>
          <view>
            <tui-input
              type="password"
              v-model="miyao"
              :labelSize="28"
              :size="28"
              placeholder="请输入密钥"
            ></tui-input>
          </view>
        </view>
      </view>

      <!-- <tui-divider>1手100股</tui-divider> -->

      <view class="flex justify-around margin-top">
        <tui-button
          @click="showModal = false"
          type="theme"
          plain
          width="160rpx"
          height="80rpx"
          :size="30"
          >取消</tui-button
        >
        <tui-button
          :loading="submiting"
          :disabled="submiting"
          @click="buy"
          type="theme"
          width="160rpx"
          height="80rpx"
          :size="30"
          >确定</tui-button
        >
      </view>
    </tui-modal>
  </view>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import { tradeList, tradeAdd } from '@/api/index.js';
  import {
    getMarketCode,
    formatNumberUnit,
    getAllCode,
    getShortCode,
    manyAccAdd,
    manyAccMul,
  } from '@/utils/stock.js';
  import { onPageScroll, onReachBottom } from '@dcloudio/uni-app';
  import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
  import { useUserStore, useMainStore } from '@/store';
  import tHeader from '@/components/views/t-header/index.vue';
  import tui from '@/common/httpRequest.js';

  // 状态管理
  const store = useUserStore();
  const mainStore = useMainStore();
  const userInfo = computed(() => store.$state.userInfo);

  const sysConfig = computed(() => mainStore.$state.sysConfig);
  console.log('sysConfig', sysConfig.value);

  // 响应式数据
  const submiting = ref(false);
  const showModal = ref(false);
  const currentItem = ref(null);
  const handNum = ref(0);
  const miyao = ref('');
  const list = ref([]);
  const title = ref('大宗交易');
  const currentTab = ref(0); // 补充原代码缺失的currentTab

  // Mescroll配置
  const { mescrollInit, downCallback, getMescroll } = useMescroll(
    onPageScroll,
    onReachBottom
  );

  // mescroll-body 配置（down && up）
  const downOption = {
    auto: false,
  };
  const upOption = {
    auto: false,
    empty: {
      use: false,
    },
  };

  const onRecord = () => {
    uni.navigateTo({
      url: '/pages/dzjy/dzjy-record',
    });
  };

  // 计算属性
  const max = computed(() => {
    if (!currentItem.value) return 0;
    const maxNum = parseInt(
      (userInfo.value.property_money / currentItem.value.cai_buy) * 100
    );
    return Math.min(maxNum, currentItem.value?.max_num || 0);
  });

  const frozenMoey = computed(() => {
    return currentItem.value
      ? manyAccMul(handNum.value, 100, currentItem.value.cai_buy)
      : 0;
  });

  // 生命周期
  onLoad((options) => {
    if (options.name) title.value = options.name;
  });

  onShow(() => {
    store.syncUserInfo();
  });

  // 方法
  const changeHandNum = (e) => {
    handNum.value = e.value;
  };

  const buy = async () => {
    if (!handNum.value) {
      tui.toast('请输入正确的手数');
      return;
    }

    if (currentItem.value?.conditioncode && !miyao.value) {
      tui.toast('请输入正确的密钥');
      return;
    }

    const postData = {
      code: getShortCode(currentItem.value.allcode),
      allMoney: manyAccMul(
        sysConfig.value.dz_dzsxf,
        handNum.value,
        100,
        currentItem.value.cai_buy
      ),
      allcode: getAllCode(currentItem.value.allcode),
      buyprice: currentItem.value.cai_buy,
      canBuy: handNum.value,
      cityValue: frozenMoey.value,
      is_auto_money: 1,
      is_buy: 1,
      is_sell: 0,
      losePrice: 0,
      money: manyAccAdd(
        frozenMoey.value,
        manyAccMul(
          sysConfig.value.dz_dzsxf,
          handNum.value,
          100,
          currentItem.value.cai_buy
        )
      ),
      multiplying: 1,
      number: handNum.value * 100,
      profitPrice: 0,
      recommendnum: frozenMoey.value,
      strategy_id: getAllCode(currentItem.value.allcode),
      title: currentItem.value.title,
      creditMoney: frozenMoey.value,
      miyao: miyao.value,
      jiami: 1,
    };

    submiting.value = true;
    try {
      const res = await tradeAdd(postData);
      tui.modal('提示', res.msg, false, () => {
        submiting.value = false;
        if (res.code === 1) {
          uni.redirectTo({
            url:
              sysConfig.value.is_weituo == 1
                ? '/pages/shares/entrustDetail'
                : './dzjy-record',
          });
        }
      });

      // tui.modal({
      //   title: null,
      //   content: res.data.msg,
      //   showCancel: false,
      //   confirm: () => {
      //     submiting.value = false;
      //     if (res.data.code === 1) {
      //       uni.redirectTo({
      //         url:
      //           sysConfig.value.is_weituo == 1
      //             ? 'pages/shares/entrustDetail'
      //             : './dzjy-record',
      //       });
      //     }
      //   },
      // });
    } catch (error) {
      console.log('error', error);

      submiting.value = false;
      tui.toast('操作失败，请重试');
    }
  };

  const showBuy = (e) => {
    currentItem.value = list.value[e.index];
    console.log('DD', currentItem.value, list.value, e);
    showModal.value = true;
  };

  const back = () => {
    uni.navigateBack();
  };

  const jump = (url) => {
    uni.navigateTo({ url });
  };

  // 修改后的上拉加载
  const upCallback = async (mescroll) => {
    try {
      const res = await tradeList({
        page: mescroll.num,
        status: currentTab.value,
        size: mescroll.size,
      });

      if (mescroll.num === 1) list.value = [];

      if (res.data?.list) {
        res.data.list.forEach((v) => {
          v.marketCode = getMarketCode(v.allcode);
          v.progress = (v.totalbuy * 100) / v.totalzfanum + '%';
        });
        list.value = [...list.value, ...res.data.list];
      }

      mescroll.endSuccess(res.data?.list?.length || 0);
    } catch (error) {
      mescroll.endErr();
    }
  };

  // 初始化Mescroll回调
  onMounted(() => {
    downCallback();
    // downCallback.value = () => getMescroll().resetUpScroll()
    // upCallback.value = loadData
  });
</script>

<style lang="scss" scoped>
  .wrapper {
    background: #f5f5f5;
  }
  .nav-box {
    padding-left: 18rpx;
    display: flex;
    align-items: center;
    margin-top: 24rpx;
    &-title {
      margin-left: 14rpx;
      font-size: 44rpx;
      font-weight: 500;
      color: #000;
    }
  }
  .main-content {
    width: 100%;

    .list-group {
      margin: 24rpx 16rpx 30rpx 18rpx;
      border-radius: 34rpx;
      padding: 0 24rpx 0 18rpx;
      background: #fff;
      .list-item {
        font-size: 24rpx;
        font-weight: 600;
        border-bottom: 2rpx solid #ddd;
        padding: 16rpx 0;
        margin-bottom: 8rpx;
        .icon-1 {
          background: blueviolet;
          width: 24rpx;
          height: 24rpx;
          font-size: 16rpx;
          color: #fff;
          font-weight: 300;
          margin-right: 4rpx;
        }
      }
      .empty-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        position: absolute;
        top: 20%;
        left: 50%;
        transform: translateX(-50%);

        > img {
          margin-bottom: 26rpx;
        }

        > text {
          color: #b6b6b6;
          font-size: 28rpx;
          font-weight: 400;
          font-family: PingFangSC, PingFang SC;
        }
      }
    }
  }
  .head {
    padding: 40rpx 0 20rpx 0;
    font-size: 26rpx;
    color: #8f8f8f;
    font-weight: 400;
    border-bottom: 2rpx solid #e2e2e2;
  }
  .item {
    font-size: 26rpx;
    font-weight: bold;
    background: #fff;
    padding: 24rpx 0;
    color: #000;
    border-bottom: 4rpx solid #ededed;
    .sign {
      width: 28rpx;
      height: 28rpx;
      margin-right: 10rpx;
    }
    .name {
      font-size: 24rpx;
      font-weight: 500;
      color: #1e1e1e;
    }
    .red {
      color: #f13444;
    }
    .green {
      color: #2ba039;
    }
  }
  .progress {
    position: relative;
    flex: 1;
    margin-right: 10rpx;
    height: 20rpx;
    border-radius: 20rpx;
    background: #f7f7f7;
    overflow: hidden;
    .bar {
      position: absolute;
      background: #f42f3c;
      left: 0;
      top: 0;
      height: 100%;
    }
  }
  .cell {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    justify-content: space-between;
    view:first-child {
      color: #999;
    }
  }
</style>
